<template>
  <div class="data-container">
    <!-- 顶部导航栏 -->
    <div class="top-bar">
      <div class="back-btn" @click="goBack">
        <i class="fas fa-arrow-left"></i>
      </div>
      <div class="page-title">数据统计</div>
      <div class="date-filter">
        <select v-model="selectedPeriod" @change="loadData" class="period-select">
          <option value="today">今日</option>
          <option value="week">本周</option>
          <option value="month">本月</option>
        </select>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="content">
      <!-- 数据概览卡片 -->
      <div class="card">
        <div class="card-header">
          <div class="card-title">
            <i class="fas fa-chart-line"></i>
            经营概览
            <span v-if="selectedBusiness" style="font-size: 14px; color: #666; margin-left: 10px;">
              - {{ selectedBusiness.businessName }}
            </span>
          </div>
        </div>

        <div class="card-body">
          <div v-if="loading" class="loading">
            <i class="fas fa-spinner fa-spin"></i> 加载数据中...
          </div>

          <div v-else class="kpi-grid">
            <div class="kpi-item">
              <div class="kpi-value">{{ overviewData.totalOrders }}</div>
              <div class="kpi-label">总订单数</div>
              <div class="kpi-change" :class="getChangeClass(overviewData.orderChange)">
                <i :class="getChangeIcon(overviewData.orderChange)"></i>
                {{ Math.abs(overviewData.orderChange) }}%
              </div>
            </div>

            <div class="kpi-item">
              <div class="kpi-value">¥{{ overviewData.totalRevenue.toFixed(2) }}</div>
              <div class="kpi-label">总收入</div>
              <div class="kpi-change" :class="getChangeClass(overviewData.revenueChange)">
                <i :class="getChangeIcon(overviewData.revenueChange)"></i>
                {{ Math.abs(overviewData.revenueChange) }}%
              </div>
            </div>

            <div class="kpi-item">
              <div class="kpi-value">¥{{ overviewData.avgOrderValue.toFixed(2) }}</div>
              <div class="kpi-label">平均订单价</div>
            </div>

            <div class="kpi-item">
              <div class="kpi-value">{{ overviewData.completionRate }}%</div>
              <div class="kpi-label">订单完成率</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 订单趋势图表 -->
      <div class="card">
        <div class="card-header">
          <div class="card-title">
            <i class="fas fa-chart-bar"></i>
            订单趋势
          </div>
        </div>
        <div class="card-body">
          <div class="chart-container">
            <canvas ref="orderTrendChart" width="400" height="200"></canvas>
          </div>
        </div>
      </div>

      <!-- 订单状态分布 -->
      <div class="card">
        <div class="card-header">
          <div class="card-title">
            <i class="fas fa-chart-pie"></i>
            订单状态分布
          </div>
        </div>
        <div class="card-body">
          <div class="chart-container">
            <canvas ref="orderStatusChart" width="400" height="200"></canvas>
          </div>
          <div class="status-legend">
            <div v-for="status in orderStatusData" :key="status.status" class="legend-item">
              <span class="status-color" :style="{ backgroundColor: status.color }"></span>
              <span class="status-text">{{ status.status }}: {{ status.count }}单 ({{ status.percentage }}%)</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 热门商品 -->
      <div class="card">
        <div class="card-header">
          <div class="card-title">
            <i class="fas fa-utensils"></i>
            热门商品
          </div>
        </div>
        <div class="card-body">
          <div v-if="topProducts.length === 0" class="empty-state">
            <i class="fas fa-utensils"></i>
            <p>暂无销售数据</p>
          </div>
          <div v-else class="product-rankings">
            <div v-for="(product, index) in topProducts" :key="product.foodId" class="product-ranking-item">
              <div class="rank-badge" :class="getRankClass(index + 1)">
                {{ index + 1 }}
              </div>
              <div class="product-info">
                <div class="product-name">{{ product.foodName }}</div>
                <div class="product-stats">
                  <span class="sales-count">销量: {{ product.salesCount }}</span>
                  <span class="revenue">收入: ¥{{ product.totalRevenue.toFixed(2) }}</span>
                </div>
              </div>
              <div class="revenue-percentage">
                {{ product.percentage }}%
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作栏 -->
    <div class="bottom-bar">
      <div
          class="bottom-btn"
          :class="{ active: activeTab === 'home' }"
          @click="setActiveTab('home')"
      >
        <i class="fas fa-home"></i>
        <span>首页</span>
      </div>

      <div
          class="bottom-btn"
          :class="{ active: activeTab === 'orders' }"
          @click="setActiveTab('orders')"
      >
        <i class="fas fa-clipboard-list"></i>
        <span>订单</span>
      </div>
      <div
          class="bottom-btn"
          :class="{ active: activeTab === 'data' }"
          @click="setActiveTab('data')"
      >
        <i class="fas fa-chart-line"></i>
        <span>数据</span>
      </div>
      <div
          class="bottom-btn"
          :class="{ active: activeTab === 'profile' }"
          @click="setActiveTab('profile')"
      >
        <i class="fas fa-user"></i>
        <span>我的</span>
      </div>
    </div>

    <!-- 通知 -->
    <div v-if="showNotification" class="notification">
      <i class="fas fa-check-circle"></i> {{ notificationMessage }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { orderAPI } from '@/api/order.js'
import { Chart } from 'chart.js/auto'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const activeTab = ref('data')
const selectedPeriod = ref('week')
const showNotification = ref(false)
const notificationMessage = ref('')
const selectedBusiness = ref(JSON.parse(sessionStorage.getItem('business') || '{}'))

// 数据相关
const overviewData = ref({
  totalOrders: 0,
  totalRevenue: 0,
  avgOrderValue: 0,
  completionRate: 0,
  orderChange: 0,
  revenueChange: 0
})

const orderTrendData = ref([])
const orderStatusData = ref([])
const topProducts = ref([])

// 图表引用
const orderTrendChart = ref(null)
const orderStatusChart = ref(null)

// 图表实例
let trendChartInstance = null
let statusChartInstance = null

// 获取当前商家ID
const getCurrentBusinessId = () => {
  return selectedBusiness.value.id || selectedBusiness.value.businessId
}

// 加载数据
const loadData = async () => {
  if (!getCurrentBusinessId()) {
    showNotificationMessage('请先选择商家')
    return
  }

  try {
    loading.value = true

    // 获取商家订单数据
    const businessId = getCurrentBusinessId()
    const response = await orderAPI.listOrdersByBusinessId(businessId)

    if (response.data && response.data.success) {
      const ordersData = response.data.data || response.data
      const orders = Array.isArray(ordersData) ? ordersData : []

      // 处理数据
      processOrderData(orders)
      updateCharts()
    } else {
      throw new Error('获取订单数据失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    showNotificationMessage('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 处理订单数据
const processOrderData = (orders) => {
  if (!orders.length) {
    resetData()
    return
  }

  // 过滤有效订单（非取消和拒绝的订单）
  const validOrders = orders.filter(order => order.orderState !== 4 && order.orderState !== 5)

  // 计算概览数据
  calculateOverview(validOrders)

  // 计算订单趋势
  calculateOrderTrend(validOrders)

  // 计算订单状态分布
  calculateOrderStatus(orders)

  // 计算热门商品
  calculateTopProducts(validOrders)
}

// 重置数据
const resetData = () => {
  overviewData.value = {
    totalOrders: 0,
    totalRevenue: 0,
    avgOrderValue: 0,
    completionRate: 0,
    orderChange: 0,
    revenueChange: 0
  }
  orderTrendData.value = []
  orderStatusData.value = []
  topProducts.value = []
}

// 计算概览数据
const calculateOverview = (orders) => {
  const totalOrders = orders.length
  const completedOrders = orders.filter(order => order.orderState === 3).length
  const totalRevenue = orders.reduce((sum, order) => sum + (order.orderTotal || 0), 0)

  overviewData.value = {
    totalOrders,
    totalRevenue,
    avgOrderValue: totalOrders > 0 ? totalRevenue / totalOrders : 0,
    completionRate: totalOrders > 0 ? Math.round((completedOrders / totalOrders) * 100) : 0,
    orderChange: calculateChange(orders, 'count'),
    revenueChange: calculateChange(orders, 'revenue')
  }
}

// 计算变化率（简化实现）
const calculateChange = (orders, type) => {
  const currentValue = type === 'count' ? orders.length :
      orders.reduce((sum, order) => sum + (order.orderTotal || 0), 0)

  // 模拟变化率
  return Math.random() * 20 - 10 // -10% 到 +10% 的随机变化
}

// 计算订单趋势
const calculateOrderTrend = (orders) => {
  // 按日期分组（简化实现）
  const last7Days = getLastNDays(7)
  const dailyData = last7Days.map(date => ({
    date,
    count: orders.filter(order => isSameDay(order.orderDate, date)).length
  }))

  orderTrendData.value = dailyData
}

// 计算订单状态分布
const calculateOrderStatus = (orders) => {
  const statusMap = {
    0: { text: '待接单', color: '#ff9800' },
    1: { text: '已接单', color: '#2196f3' },
    2: { text: '配送中', color: '#673ab7' },
    3: { text: '已完成', color: '#4caf50' },
    4: { text: '已取消', color: '#f44336' },
    5: { text: '已拒绝', color: '#9e9e9e' }
  }

  const statusCounts = {}
  orders.forEach(order => {
    const status = order.orderState
    statusCounts[status] = (statusCounts[status] || 0) + 1
  })

  const total = orders.length
  orderStatusData.value = Object.entries(statusCounts).map(([status, count]) => ({
    status: statusMap[status]?.text || `状态${status}`,
    count,
    percentage: total > 0 ? Math.round((count / total) * 100) : 0,
    color: statusMap[status]?.color || '#666'
  }))
}

// 计算热门商品
const calculateTopProducts = (orders) => {
  const productMap = {}

  orders.forEach(order => {
    if (order.foods && Array.isArray(order.foods)) {
      order.foods.forEach(food => {
        if (!productMap[food.foodId]) {
          productMap[food.foodId] = {
            foodId: food.foodId,
            foodName: food.foodName,
            salesCount: 0,
            totalRevenue: 0
          }
        }
        productMap[food.foodId].salesCount += food.quantity || 1
        productMap[food.foodId].totalRevenue += (food.foodPrice || 0) * (food.quantity || 1)
      })
    }
  })

  const products = Object.values(productMap)
  const totalRevenue = products.reduce((sum, product) => sum + product.totalRevenue, 0)

  // 按销售额排序并计算百分比
  topProducts.value = products
      .sort((a, b) => b.totalRevenue - a.totalRevenue)
      .slice(0, 5)
      .map(product => ({
        ...product,
        percentage: totalRevenue > 0 ? Math.round((product.totalRevenue / totalRevenue) * 100) : 0
      }))
}

// 更新图表
const updateCharts = () => {
  updateTrendChart()
  updateStatusChart()
}

// 更新趋势图表
const updateTrendChart = () => {
  if (trendChartInstance) {
    trendChartInstance.destroy()
  }

  const ctx = orderTrendChart.value?.getContext('2d')
  if (!ctx) return

  trendChartInstance = new Chart(ctx, {
    type: 'line',
    data: {
      labels: orderTrendData.value.map(item => formatChartDate(item.date)),
      datasets: [{
        label: '订单数量',
        data: orderTrendData.value.map(item => item.count),
        borderColor: '#0097ff',
        backgroundColor: 'rgba(0, 151, 255, 0.1)',
        tension: 0.4,
        fill: true
      }]
    },
    options: {
      responsive: true,
      plugins: {
        legend: {
          display: false
        }
      },
      scales: {
        y: {
          beginAtZero: true,
          ticks: {
            stepSize: 1
          }
        }
      }
    }
  })
}

// 更新状态分布图表
const updateStatusChart = () => {
  if (statusChartInstance) {
    statusChartInstance.destroy()
  }

  const ctx = orderStatusChart.value?.getContext('2d')
  if (!ctx) return

  statusChartInstance = new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: orderStatusData.value.map(item => item.status),
      datasets: [{
        data: orderStatusData.value.map(item => item.count),
        backgroundColor: orderStatusData.value.map(item => item.color)
      }]
    },
    options: {
      responsive: true,
      plugins: {
        legend: {
          display: false
        }
      }
    }
  })
}

// 工具函数
const getLastNDays = (n) => {
  const days = []
  for (let i = n - 1; i >= 0; i--) {
    const date = new Date()
    date.setDate(date.getDate() - i)
    days.push(date.toISOString().split('T')[0])
  }
  return days
}

const isSameDay = (dateString, targetDate) => {
  if (!dateString) return false
  const date = new Date(dateString)
  return date.toISOString().split('T')[0] === targetDate
}

const formatChartDate = (dateString) => {
  const date = new Date(dateString)
  return `${date.getMonth() + 1}/${date.getDate()}`
}

const getChangeClass = (change) => {
  return change >= 0 ? 'positive' : 'negative'
}

const getChangeIcon = (change) => {
  return change >= 0 ? 'fas fa-arrow-up' : 'fas fa-arrow-down'
}

const getRankClass = (rank) => {
  if (rank === 1) return 'rank-1'
  if (rank === 2) return 'rank-2'
  if (rank === 3) return 'rank-3'
  return 'rank-other'
}

// 显示通知消息
const showNotificationMessage = (message) => {
  notificationMessage.value = message
  showNotification.value = true
  setTimeout(() => {
    showNotification.value = false
  }, 3000)
}

// 导航功能
const goBack = () => {
  router.go(-1)
}

const setActiveTab = (tab) => {
  activeTab.value = tab
  switch (tab) {
    case 'home':
      router.push('/BusinessEnd')
      break
    case 'orders':
      router.push('/business-orders')
      break
    case 'data':
      // 当前页面
      break
    case 'profile':
      router.push('/business-profile')
      break
  }
}

// 生命周期
onMounted(() => {
  if (getCurrentBusinessId()) {
    loadData()
  } else {
    showNotificationMessage('请先在商家管理页面选择商家')
  }
})
</script>

<style scoped>
.data-container {
  max-width: 400px;
  margin: 0 auto;
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 70px;
}

/* 顶部导航 */
.top-bar {
  position: sticky;
  top: 0;
  width: 100%;
  max-width: 360px;
  height: 50px;
  background: linear-gradient(90deg, #0088ff, #00bbff);
  color: white;
  display: flex;
  align-items: center;
  padding: 0 15px;
  z-index: 100;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.back-btn {
  font-size: 18px;
  margin-right: 15px;
  cursor: pointer;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  flex:0.9;
}

.date-filter {
  margin-left: auto;
}

.period-select {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 6px;
  padding: 4px 8px;
  color: white;
  font-size: 14px;
}

.period-select option {
  color: #333;
}

/* 主内容区域 */
.content {
  padding: 15px;
}

/* 卡片样式 */
.card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
  margin-bottom: 15px;
  overflow: hidden;
}

.card-header {
  padding: 15px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f8f9fa;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  display: flex;
  align-items: center;
}

.card-title i {
  margin-right: 8px;
  color: #0097ff;
}

.card-body {
  padding: 15px;
}

/* KPI网格 */
.kpi-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.kpi-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  text-align: center;
  border-left: 4px solid #0097ff;
}

.kpi-value {
  font-size: 20px;
  font-weight: 700;
  color: #333;
  margin-bottom: 5px;
}

.kpi-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.kpi-change {
  font-size: 11px;
  font-weight: 600;
}

.kpi-change.positive {
  color: #4caf50;
}

.kpi-change.negative {
  color: #f44336;
}

.kpi-change i {
  margin-right: 2px;
}

/* 图表容器 */
.chart-container {
  height: 200px;
  position: relative;
}

/* 状态图例 */
.status-legend {
  margin-top: 15px;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 13px;
}

.status-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 8px;
}

.status-text {
  color: #666;
}

/* 商品排名 */
.product-rankings {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.product-ranking-item {
  display: flex;
  align-items: center;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 8px;
}

.rank-badge {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 700;
  color: white;
  margin-right: 12px;
}

.rank-1 {
  background: #ffd700;
}

.rank-2 {
  background: #c0c0c0;
}

.rank-3 {
  background: #cd7f32;
}

.rank-other {
  background: #666;
}

.product-info {
  flex: 1;
}

.product-name {
  font-weight: 600;
  font-size: 14px;
  margin-bottom: 4px;
}

.product-stats {
  display: flex;
  gap: 10px;
  font-size: 12px;
  color: #666;
}

.revenue-percentage {
  font-weight: 600;
  color: #0097ff;
  font-size: 14px;
}

/* 加载和空状态 */
.loading {
  text-align: center;
  padding: 40px;
  color: #0097ff;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #777;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 15px;
  color: #ddd;
}

/* 底部操作栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  width: 100%;
  max-width: 396px;
  height: 60px;
  background-color: white;
  display: flex;
  justify-content: space-around;
  align-items: center;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.bottom-btn {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 8px;
  color: #666;
  font-size: 12px;
  text-align: center;
  transition: color 0.2s;
}

.bottom-btn i {
  font-size: 20px;
  margin-bottom: 3px;
}

.bottom-btn.active {
  color: #0097ff;
}

.bottom-btn:active {
  transform: scale(0.95);
}

/* 通知 */
.notification {
  position: fixed;
  top: 60px;
  left: 50%;
  transform: translateX(-50%);
  padding: 12px 20px;
  background-color: #4caf50;
  color: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 300;
  animation: slideIn 0.3s, fadeOut 0.5s 2.5s;
}

@keyframes slideIn {
  from {
    top: 0;
    opacity: 0;
  }
  to {
    top: 60px;
    opacity: 1;
  }
}

@keyframes fadeOut {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}
</style>